#import "eBookrController.h"

@implementation eBookrController

- (void)awakeFromNib
{
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(defaultBookFolderDidChange:) 
		name:DEFAULT_FOLDER_CHANGED object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(iphoneWasAttached:) 
		name:IPHONE_CONNECTED object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(iphoneWasRemoved:) 
		name:IPHONE_DISCONNECTED object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(iphoneSentError:) 
												 name:IPHONE_ERROR object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(iphoneSentMessage:) 
												 name:IPHONE_MESSAGE object:nil];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tableSelectionDidChange:)
												 name:NSTableViewSelectionDidChangeNotification object:nil];
		
	gutenMarker = [[GutenMarkController alloc] init];
	iphoneController = [[MobileDeviceController alloc] init];
	
	[progressPanelIndicator setUsesThreadedAnimation:YES];
	[copyToPhoneProgressIndicator setUsesThreadedAnimation:YES];
	[copyFromPhoneProgressIndicator setUsesThreadedAnimation:YES];
	filesInTable = [[NSMutableArray alloc] init];
	[filesTable registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]];
	filesOnPhone = [[NSMutableArray alloc] init];
}

- (void)tableSelectionDidChange:(NSNotification *)notification
{
	[removeSelectedFilesFromTableButton setEnabled:[filesTable numberOfSelectedRows]];
}

- (void)defaultBookFolderDidChange:(NSNotification *)aNotification
{
	NSLog(@"defaultBookFolderDidChange");	
}

- (void)iphoneWasAttached:(NSNotification *)aNotification
{
	[sendToPhoneButton setEnabled:YES];
	[copyFromPhoneButton setEnabled:YES];
	
	[iphoneStatusText setStringValue:@"Reading iPhone..."];
	[iphoneStatusText display];
	[copyFromPhoneProgressIndicator startAnimation:self];
	[filesOnPhone setArray:[iphoneController booksInRootFolder]];
	[iphoneTable reloadData];
	[iphoneStatusText setStringValue:@"iPhone connected."];
	[copyFromPhoneProgressIndicator stopAnimation:self];
}

- (void)iphoneWasRemoved:(NSNotification *)aNotification
{
	[iphoneStatusText setStringValue:@"iPhone disconnected."];
	[sendToPhoneButton setEnabled:NO];
	[copyFromPhoneButton setEnabled:NO];
	
	[filesOnPhone removeAllObjects];
	[iphoneTable reloadData];
}

- (void)iphoneSentError:(NSNotification *)aNotification
{
	NSDictionary *info = [aNotification userInfo];
	if (nil == info)
		[iphoneStatusText setStringValue:@"Unknown iPhone error."];
	else
	{
		[iphoneStatusText setStringValue:[info objectForKey:ERRORMESSAGE_KEY]];
	}
	[iphoneStatusText display];
	[sendToPhoneButton setEnabled:NO];
	[copyFromPhoneButton setEnabled:NO];
}

- (void)iphoneSentMessage:(NSNotification *)aNotification
{
	NSDictionary *info = [aNotification userInfo];
	if (nil == info)
		[iphoneStatusText setStringValue:@"Unknown iPhone message."];
	else
	{
		[iphoneStatusText setStringValue:[info objectForKey:ERRORMESSAGE_KEY]];
	}
	[iphoneStatusText display];
}

- (IBAction)chooseTextFile:(id)sender
{
	NSArray *fileTypes = [NSArray arrayWithObjects:@"txt", @"TXT", nil];
	NSOpenPanel *openPanel = [NSOpenPanel openPanel];
	[openPanel setAllowsMultipleSelection:NO];
	[openPanel setCanChooseDirectories:NO];
	[[NSOpenPanel openPanel] beginSheetForDirectory:nil file:nil types:fileTypes modalForWindow:mainWin modalDelegate:self didEndSelector:@selector(openPanelDidEnd: returnCode: contextInfo:) contextInfo:NULL];
}

- (void)openPanelDidEnd:(NSOpenPanel *)panel returnCode:(int)returnCode  contextInfo:(void  *)contextInfo
{
	if (NSOKButton == returnCode)
	{
		NSString *theFile = [[panel filenames] objectAtIndex:0];
		[gutenbergTextPath setStringValue:theFile];
		[convertButton setEnabled:YES];
	}
}

- (IBAction)copyAllBooksFromPhone:(id)sender
{
	NSOpenPanel *openPanel = [NSOpenPanel openPanel];
	[openPanel setCanChooseDirectories:YES];
	[openPanel setCanCreateDirectories:YES];
	[openPanel setCanChooseFiles:NO];
	[openPanel setAllowsMultipleSelection:NO];
	[openPanel setPrompt:@"Choose"];
	[openPanel setTitle:@"Choose a directory in which to save."];
	[openPanel beginSheetForDirectory:nil file:nil types:nil
					   modalForWindow:mainWin
						modalDelegate:self
					   didEndSelector:@selector(copyBooksPanelDidEnd: returnCode: contextInfo:)
						  contextInfo:NULL];
}

- (void)copyBooksPanelDidEnd:(NSOpenPanel *)panel returnCode:(int)returnCode  contextInfo:(void  *)contextInfo
{
	NSLog(@"copyBooksPanelDidEnd");
	if (NSOKButton == returnCode)
	{
		NSString *basePath = [[panel filenames] objectAtIndex:0];
		[panel orderOut:self];
		[copyFromPhoneProgressIndicator startAnimation:self];
		NSArray *arrayOfFilenames = [iphoneController saveBooksFromPhoneToLocalPath:basePath];
		[filesInTable addObjectsFromArray:arrayOfFilenames]; //FIXME
		[filesTable reloadData];
		[copyFromPhoneProgressIndicator stopAnimation:self];
		NSString *message = [NSString stringWithFormat:@"Copied %d items.", [arrayOfFilenames count]];
		[iphoneStatusText setStringValue:message];
	}
}

- (IBAction)doConvert:(id)sender
{
	NSSavePanel *savePanel = [NSSavePanel savePanel];
	[savePanel setRequiredFileType:@"html"];
	[savePanel setCanCreateDirectories:YES];
	[savePanel setCanSelectHiddenExtension:YES];
	[savePanel beginSheetForDirectory:nil 
								 file:nil 
					   modalForWindow:mainWin 
						modalDelegate:self 
					   didEndSelector:@selector(savePanelDidEnd: returnCode: contextInfo:) 
						  contextInfo:NULL];
}

- (void)doGutenMarkForNotification:(NSNotification *)aNotification
{
}

- (void)savePanelDidEnd:(NSSavePanel *)sheet returnCode:(int)returnCode  contextInfo:(void  *)contextInfo
{
	if (NSOKButton == returnCode)
	{
		NSString *outPath = [sheet filename];
		NSString *inPath = [gutenbergTextPath stringValue];
		[sheet orderOut:self];
		[NSApp beginSheet:progressPanel modalForWindow:mainWin 
			modalDelegate:self didEndSelector:nil contextInfo:NULL];
		[progressPanelIndicator startAnimation:self];
		int result = [gutenMarker markupFileAtPath:inPath savePath:outPath];
		//int result = 1;  //Just testin'.
		if (result)
		{
			[[NSAlert alertWithMessageText:@"Sorry." 
							 defaultButton:@"Shucks" 
						   alternateButton:nil otherButton:nil 
				 informativeTextWithFormat:@"Bummer, dude, it didn't work."] runModal];
		}
		[progressPanelIndicator stopAnimation:self];
		[NSApp endSheet:progressPanel];	
		[progressPanel orderOut:self];
		[splitterPath setStringValue:outPath];
		if ([openHTMLCheckBox state] == NSOnState)
		{
			[[NSWorkspace sharedWorkspace] openFile:outPath];
		}
	}
}

- (IBAction)doSplit:(id)sender
{
	NSOpenPanel *openPanel = [NSOpenPanel openPanel];
	[openPanel setCanChooseDirectories:YES];
	[openPanel setCanCreateDirectories:YES];
	[openPanel setCanChooseFiles:NO];
	[openPanel setAllowsMultipleSelection:NO];
	[openPanel setPrompt:@"Choose"];
	[openPanel setTitle:@"Choose a directory in which to save."];
	[openPanel beginSheetForDirectory:nil file:nil types:nil
					   modalForWindow:mainWin
						modalDelegate:self
					   didEndSelector:@selector(selectSplitPanelDidEnd: returnCode: contextInfo:)
						  contextInfo:NULL];
	
}
- (void)selectSplitPanelDidEnd:(NSOpenPanel *)panel returnCode:(int)returnCode  contextInfo:(void  *)contextInfo
{
	NSLog(@"selectSplitPanelDidEnd");
	if (NSOKButton == returnCode)
	{
		NSString *folder = [[panel filenames] objectAtIndex:0];
		[panel orderOut:self];
		NSMutableDictionary *opts = [[NSMutableDictionary alloc] init];
		NSString *splitTypeString = [NSString stringWithFormat:@"%d", [splitTypeMenu indexOfSelectedItem]];
		[opts setObject:splitTypeString forKey:SPLIT_TYPE_KEY];
		
		TextSplitter *splitter = [[TextSplitter alloc] initWithOptionsDictionary:opts];
		BOOL yesorno = [splitter splitFile:[splitterPath stringValue] toDirectory:folder];
		if (NO == yesorno)
		{
			[NSAlert alertWithMessageText:@"Sorry" defaultButton:nil alternateButton:nil 
							  otherButton:nil informativeTextWithFormat:@"Didn't work."];
		}
		[splitter release];
		[opts release];
	}
}

- (IBAction)sendBooksToPhone:(id)sender
{
	int count = [filesInTable count];
	if (count)
	{
		[iphoneStatusText setStringValue:@"Copying books to iPhone..."];
		[iphoneStatusText display];
		[copyToPhoneProgressIndicator startAnimation:self];
		int ret = [iphoneController copyTheseFiles:filesInTable]; /// boing boing
		[iphoneStatusText setStringValue:[NSString stringWithFormat:@"Copied %d of %d items.", ret, count]];
		[copyToPhoneProgressIndicator stopAnimation:self];
		[filesTable deselectAll:self];
		[filesInTable removeAllObjects];
		[filesTable reloadData];
		[filesOnPhone setArray:[iphoneController booksInRootFolder]];
		[iphoneTable reloadData];
	}
}

- (IBAction)addFilesToFilesTable:(id)sender
{
	NSOpenPanel *openPanel = [NSOpenPanel openPanel];
	[openPanel setAllowsMultipleSelection:YES];
	[openPanel setCanChooseDirectories:YES];
	[openPanel setCanChooseFiles:YES];
	NSArray *allowedTypes = [NSArray arrayWithObjects:@"htm", @"html", @"txt", @"pdb", nil];
	[openPanel beginSheetForDirectory:nil file:nil types:allowedTypes
					   modalForWindow:mainWin modalDelegate:self
					   didEndSelector:@selector(addFilesPanelDidEnd: returnCode: contextInfo:)
						  contextInfo:NULL];
}

- (void)addFilesPanelDidEnd:(NSOpenPanel *)panel returnCode:(int)returnCode  contextInfo:(void  *)contextInfo
{
	if (NSOKButton == returnCode)
	{
		NSArray *filenames = [panel filenames];
		NSEnumerator *enumerator = [filenames objectEnumerator];
		id i;
		while (i = [enumerator nextObject])
		{
			if (![filesInTable containsObject:i])
				[filesInTable addObject:i];
		}
		[filesTable reloadData];
	}
}

- (IBAction)removeSelectedFilesFromFilesTable:(id)sender
{
	//FIXME: Figure out how to make the Delete key send this action
	NSIndexSet *selectedIndexes = [filesTable selectedRowIndexes];
	[filesInTable removeObjectsAtIndexes:selectedIndexes];
	[filesTable reloadData];
	[filesTable deselectAll:self];
}

// ------------- Table delegate methods.

- (NSDragOperation)tableView:(NSTableView *)tableView validateDrop:(id <NSDraggingInfo>)info proposedRow:(int)row
	   proposedDropOperation:(NSTableViewDropOperation)operation
{
	[tableView setDropRow:[filesInTable count] dropOperation:NSTableViewDropAbove];
	return NSDragOperationCopy;
}

- (BOOL)tableView:(NSTableView *)aTableView acceptDrop:(id <NSDraggingInfo>)info row:(int)row 
	dropOperation:(NSTableViewDropOperation)operation
{
	NSPasteboard *thePasteboard = [info draggingPasteboard];
	if ([[thePasteboard types] containsObject:NSFilenamesPboardType])
	{
		NSArray *files = [thePasteboard propertyListForType:NSFilenamesPboardType];
		NSEnumerator *enumerator = [files objectEnumerator];
		id i;
		while (i = [enumerator nextObject])
		{
			NSString *ext = [[i pathExtension] lowercaseString];
			//NSLog(@"ext: %@", ext);
			BOOL isDir;
			BOOL unused = [[NSFileManager defaultManager] fileExistsAtPath:i isDirectory:&isDir];
			if ((!isDir) && (!([ext isEqualToString:@"htm"] || [ext isEqualToString:@"html"] || 
				  [ext isEqualToString:@"txt"] || [ext isEqualToString:@"pdb"] || [ext isEqualToString:@""])))
				return NO;
			if (![filesInTable containsObject:i])
				[filesInTable addObject:i];
		}
		[filesTable reloadData];
		return YES;
	}
	return NO;
}

- (int)numberOfRowsInTableView:(NSTableView *)tableView
{
	if (tableView == filesTable)
		return [filesInTable count];
	else
		return [filesOnPhone count];
}

- (id)tableView:(NSTableView *)aTable objectValueForTableColumn:(NSTableColumn *)col row:(int)rowIndex
{
	if (aTable == filesTable)
	{
		if ([filesInTable count])
			return [filesInTable objectAtIndex:rowIndex];
	}
	else
	{
		if ([filesOnPhone count])
			return [filesOnPhone objectAtIndex:rowIndex];
	}
}

- (void)dealloc
{
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[gutenMarker release];
	[iphoneController release];
	[filesInTable release];
	[filesOnPhone release];
	[super dealloc];
}
@end
